﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using EM.Components.Entities;

namespace EM.Components.DataAccess
{
    public class BaseDataAccess
    {
        #region variables
        public const string CON_STRING_KEY = "EMEntites";
        private string _con;
        public string ConnectionString 
        {
            get{return _con;}
            set { _con = value; }
        }

        private EMEntities _ctx;
        protected EMEntities Ctx 
        {
            get { return _ctx; }
            set { _ctx = value;}
        }
        #endregion

        public BaseDataAccess() 
        {
            this.ConnectionString = ConfigurationManager.ConnectionStrings[CON_STRING_KEY].ConnectionString;
            _ctx = CreateDataContext(this.ConnectionString);
        }

        public EMEntities CreateDataContext(string cnn)
        {
            if (string.IsNullOrEmpty(cnn)) 
            {
                throw new ArgumentNullException("String cnn", "Connection string can not be null or empty!");
            }

            var ctx = new EMEntities(cnn);
            return ctx;
        }

        /// <summary>
        /// Validate entity Id. throw exception if id is less than 1.
        /// <param name=" entityId"></param>
        /// </summary>
        public void ValidateEntityId(int entityId)
        {
            if (entityId < 1) 
            {
                throw new ArgumentNullException("int entityId","entity Id must be greater yhan 0!");
            }
        }

        public void ValidateNull<T>(T entity) 
        {
            if (entity == null) 
            {
                throw new ArgumentNullException(typeof(T).ToString() + " Entity", "entity cannot be null!");
            }
        } 

    }
}